package com.qnzw.zjmy.home.ui.activity;

import android.Manifest;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.qnzw.zjmy.BuildConfig;
import com.qnzw.zjmy.R;
import com.qnzw.zjmy.config.UrlConfig;
import com.qnzw.zjmy.utils.QrcodeUtils;
import com.qnzw.zjmy.volley.BaseActivity;
import com.qnzw.zjmy.volley.state.HUCState;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class InviteUserActivity extends BaseActivity {
    private ImageView ivQrCode;
    private View llSave;

    private TextView tvCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_invite_user);
        super.onCreate(savedInstanceState);
        tvActionbarTitle.setVisibility(View.GONE);
        String code = getSharedPreferences("code");
        tvCode.setText(code);
        Bitmap qrCode = QrcodeUtils.createQRImage(UrlConfig.URL_DOWNLOAD + "?pid=" + code+"&uvChannel="+ BuildConfig.CHANNEL_PACKAGE, 500, 500);
        ivQrCode.setImageBitmap(qrCode);
    }

    @Override
    public void initView() {
        super.initView();
        ivQrCode = findViewById(R.id.iv_qr_code);
        llSave = findViewById(R.id.ll_save);
        tvCode = findViewById(R.id.tv_code);

    }

    @Override
    public void initClick() {
        super.initClick();
        findViewById(R.id.tv_save).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_save:
                if (!(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) ||
                        !(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
                    //没有权限，申请权限
                    String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                    //申请权限，其中RC_PERMISSION是权限申请码，用来标志权限申请的
                    ActivityCompat.requestPermissions(this, permissions, HUCState.HUC_REQEUST_CODE_1);
                } else {
                    //跳转到调用系统相机
                    saveImageView(getViewBitmap(llSave));
                    loading();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == HUCState.HUC_REQEUST_CODE_1) {
            if (grantResults.length == 2
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                saveImageView(getViewBitmap(llSave));
            }
        } else {
            showToast("获取内存权限失败，保存失败！");
        }
    }

    private void saveImageView(Bitmap drawingCache) {
        Observable.create(new SaveObservable(drawingCache))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SaveSubscriber());
    }

    /**
     * 某些机型直接获取会为null,在这里处理一下防止国内某些机型返回null
     */
    private Bitmap getViewBitmap(View view) {
        if (view == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }


    private class SaveSubscriber extends Subscriber<String> {

        @Override
        public void onCompleted() {
            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
            loadDismiss();
        }

        @Override
        public void onError(Throwable e) {
            Log.i(getClass().getSimpleName(), e.toString());
            Toast.makeText(getApplicationContext(), "保存失败——> " + e.toString(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNext(String s) {
            //Toast.makeText(getApplicationContext(), "保存路径为：-->  " + s, Toast.LENGTH_SHORT).show();
        }
    }

    private class SaveObservable implements Observable.OnSubscribe<String> {

        private Bitmap drawingCache = null;

        public SaveObservable(Bitmap drawingCache) {
            this.drawingCache = drawingCache;
        }

        @Override
        public void call(Subscriber<? super String> subscriber) {
            if (drawingCache == null) {
                subscriber.onError(new NullPointerException("imageview的bitmap获取为null,请确认imageview显示图片了"));
            } else {
                try {
                    //File imageFile = new File(Environment.getExternalStorageDirectory(), "saveImageview.jpg");
                    ContextWrapper cw = new ContextWrapper(InviteUserActivity.this);
                    File directory = cw.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File imageFile = new File(directory, "save.jpg");
                    FileOutputStream outStream = new FileOutputStream(imageFile);
                    drawingCache.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
                    subscriber.onNext(imageFile.getPath());
                    subscriber.onCompleted();
                    outStream.flush();
                    outStream.close();
                    // 其次把文件插入到系统图库
                    String path = imageFile.getAbsolutePath();
                    try {
                        MediaStore.Images.Media.insertImage(InviteUserActivity.this.getContentResolver(), path, "m2.jpg", null);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    // 最后通知图库更新
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(imageFile);
                    intent.setData(uri);
                    InviteUserActivity.this.sendBroadcast(intent);
                } catch (IOException e) {
                    subscriber.onError(e);
                }
            }
        }
    }


}